package com.swsc.solarverse.cmd;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.swsc.solarverse.assembler.DefectQueryAssembler;
import com.swsc.solarverse.common.enums.SortTypeEnums;
import com.swsc.solarverse.common.model.PageInfo;
import com.swsc.solarverse.dao.entity.DefectDO;
import com.swsc.solarverse.model.DefectQueryBO;
import com.swsc.solarverse.model.req.DefectQueryReqVO;
import com.swsc.solarverse.model.res.StationDefectResVO;
import com.swsc.solarverse.service.IDefectService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

/**
 * @Author chencl
 * @Date 2021/11/27 20:43
 * @Version 1.0
 * @Description
 */
@Slf4j
@Component
public class DefectPageQueryCmdExe {
    private final DefectQueryAssembler defectQueryAssembler;
    private final IDefectService defectService;

    public DefectPageQueryCmdExe(DefectQueryAssembler defectQueryAssembler, IDefectService defectService) {
        this.defectQueryAssembler = defectQueryAssembler;
        this.defectService = defectService;
    }

    public PageInfo<StationDefectResVO> execute(DefectQueryReqVO reqVo) {
        QueryWrapper<DefectDO> wrapper = defectQueryAssembler.getQueryWapper(reqVo);

        if (SortTypeEnums.DESC.getType().equals(reqVo.getSortBy())) {
            wrapper.lambda().orderByDesc(DefectDO::getPatrolTime, DefectDO::getDealTime);

        } else {
            wrapper.lambda().orderByAsc(DefectDO::getPatrolTime, DefectDO::getDealTime);
        }

        DefectQueryBO queryBO = reqVo.map(DefectQueryBO.class);
        //PageInfo<DefectDO> pageInfo = defectService.page(queryBO,reqVo.getPageNo(), reqVo.getPageSize());


        PageInfo<DefectDO> pageInfo = defectService.page(new PageInfo<>(reqVo.getPageNo(), reqVo.getPageSize()), wrapper);

        PageInfo<StationDefectResVO> page = pageInfo.mapPage(StationDefectResVO.class);
        long count = page.getTotalCount();
        float loss = 0.0F;
        String remark = "故障数量: %s 个, 损耗统计: %s kWh/年";
        if(null != page && CollectionUtils.isNotEmpty(page.getResult())){
            wrapper.select(  " sum(loss) as loss ");
            DefectDO defectDo = defectService.getOne(wrapper);
            if(null != defectDo && null != defectDo.getLoss()){
                loss = defectDo.getLoss();
            }
        }
        page.setRemark(String.format(remark, count, loss));
        return page;
    }
}
